package ucap.com.lesanapp.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

/**
 * Created by Administrator on 2016/6/20.
 */
public class NewsTopViewPager extends ViewPager {

    private int startX;
    private int startY;

    public NewsTopViewPager(Context context) {
        super(context);
    }

    public NewsTopViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        /**
         * 1.上下滑动需要拦截。
         * 2.左滑动最后一个页面需要拦截。
         * 3.右滑动第一个页面需要拦截。
         */

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) ev.getX();
                startY = (int) ev.getY();
                getParent().requestDisallowInterceptTouchEvent(true);//父控件不要拦截滑动事件
                break;
            case MotionEvent.ACTION_MOVE:
                int endX = (int) ev.getX();
                int endY = (int) ev.getY();

                int dx = endX - startX;
                int dy = endY - startY;
                if (Math.abs(dx) > Math.abs(dy)) {//左右滑动
                    if (dx > 0) {//右滑动
                        int currentItem = getCurrentItem();
                        if (currentItem == 0) {//右滑动第一个页面拦截
                            getParent().requestDisallowInterceptTouchEvent(false);
                        }
                        Log.i("start", "startX:" + startX);
                        Log.i("start", "currentItem:" + currentItem);
                        Log.i("start", "右滑动");
                    } else {
                        //左滑动最后一个页面
                        if (getCurrentItem() == getAdapter().getCount() - 1) {
                            getParent().requestDisallowInterceptTouchEvent(false);
                        }
                        Log.i("start", "startX:" + startX);
                        Log.i("start", "currentItem:" + getCurrentItem());
                        Log.i("start", "左滑动");
                    }
                } else {//上下滑动
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;


        }
        return super.dispatchTouchEvent(ev);
    }
}
